package org.xxpay.pay.channel.xinanpay;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.entity.TransOrder;
import org.xxpay.pay.channel.BaseTrans;

import java.util.Map;
@Component
public class XinanpayTransService extends BaseTrans {
    private final static String logPrefix = "【信安支付代付】";
    @Override
    public String getChannelName() {
        return XinanpayConfig.CHANNEL_NAME;
    }
    @Override
    public JSONObject balance(String payParam) {
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有余额查询接口");
        return retObj;
    }
    /**
     * 代付订单
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject trans(TransOrder transOrder){
        JSONObject retObj = buildRetObj();
        XinanpayConfig config = new XinanpayConfig(getTransParam(transOrder));
        JSONObject params = new JSONObject();
        //设置请求参数
        setParams(transOrder,config,params);
        _log.info("{}申请代付请求参数：{}", logPrefix, params.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+XinanpayConfig.REQ_TRANS_URL_FIXX, JSONObject.parseObject(params.toString()), JSONObject.class);
        retObj.put("isSuccess", false);
        retObj.put("transOrderId", transOrder.getTransOrderId());
        if(StringUtils.equals(origin.getString("status"),"SUCCESS")){
            retObj.put("channelOrderNo", origin.getString("trade_no"));
            retObj.put("isSuccess", true);
            // 1. 处理中 2. 成功 3. 失败
            if(StringUtils.equals(origin.getString("trade_state"),"PROCESSING")) {
                retObj.put("status", 1);
            }else if(StringUtils.equals(origin.getString("trade_state"),"SUCCESS")){
                retObj.put("status", 2);
            }else{
                retObj.put("status", 3);
            }
            return retObj;
        }
        // 1. 处理中 2. 成功 3. 失败
        retObj.put("status", 3);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "下单失败[" + origin.getString("message") + "]");
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        return retObj;
    }
    /**
     * 订单查询接口
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject query(TransOrder transOrder) {
        XinanpayConfig config = new XinanpayConfig(getTransParam(transOrder));
        String payOrderId = transOrder.getTransOrderId();
        _log.info("{}开始查询代付通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("sp_id", config.getAppId());
        params.put("mch_id", config.getMchId());
        params.put("out_trade_no", transOrder.getMchTransNo());
        params.put("nonce_str", transOrder.getMchTransNo());
        params.put("sign", getSign(params, config.getPublicKey()));
        _log.info("{}代付查询请求参数：{}", logPrefix, params.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+XinanpayConfig.REQ_TRANS_QUERY_URL_FIXX, params, JSONObject.class);
        _log.info("{}代付查询响应参数：{}", logPrefix, origin.toJSONString());
        JSONObject retObj = buildRetObj();
        if(StringUtils.equals(origin.getString("status"),"SUCCESS")){
            retObj.put("isSuccess", true);
            retObj.put("transOrderId", transOrder.getTransOrderId());
            retObj.putAll(origin);

            String status = origin.getString("trade_state");
            if (StringUtils.equals(status,"SUCCESS")) {
                retObj.put("status", 2); // 2表示成功
            } else if (StringUtils.equals(status,"PROCESSING")) {
                retObj.put("status", 1); // 3表示失败
            } else {
                retObj.put("status", 3); // 1处理中
            }
            retObj.put("channelOrderNo", origin.getString("trade_no"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("message"));
        retObj.put("channelErrCode", origin.getString("status"));
        retObj.put("isSuccess", false);
        return retObj;
    }
    //设置请求参数
    private void setParams(TransOrder transOrder,XinanpayConfig config,JSONObject params){
        params.put("sp_id", config.getAppId());
        params.put("mch_id", config.getMchId());
        params.put("out_trade_no", transOrder.getMchTransNo());
        params.put("body", transOrder.getMchTransNo());
        params.put("total_fee", transOrder.getAmount());
        params.put("card_name", transOrder.getAccountName());
        params.put("card_no", transOrder.getAccountNo());
        params.put("notify_url", payConfig.getNotifyTransUrl(getChannelName()));
        params.put("df_type","0");
        params.put("nonce_str", transOrder.getMchTransNo());
        params.put("sign", getSign(params, config.getPublicKey()));
    }
    //获取sign
    private String getSign(Map<String,Object> params,String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+"&key="+key);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8).toUpperCase();
        return sign;
    }
}
